<template>
  <div ref="contentRef" class="markdown-view" v-html="renderedMarkdown"></div>
</template>

<script>
import MarkdownIt from "markdown-it";
import "highlight.js/styles/vs2015.min.css";
import hljs from "highlight.js";

export default {
  props: {
    content: {
      type: String,
      required: true,
    },
  },
  // 监听 content，当 content 改变时，强制重新渲染
  watch: {
    content: {
      immediate: true,
      handler() {
        this.updateMarkdown();
      },
    },
  },
  data() {
    return {
      renderedMarkdown: "",
    };
  },
  computed: {
    md() {
      return new MarkdownIt({
        highlight: function (str, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              const copyHtml = `<div id="copy" data-copy='${str}' style="position: absolute; right: 10px; top: 5px; color: #fff; cursor: pointer;">复制</div>`;
              return `<pre style="position: relative;">${copyHtml}<code class="hljs">${hljs.highlight(lang, str, true).value}</code></pre>`;
            } catch (__) {}
          }
          return "";
        },
      });
    },
  },
  methods: {
    updateMarkdown() {
      this.renderedMarkdown = this.md.render(this.content);
    },
    handleCopyClick(e) {
      if (e.target.id === "copy") {
        // 复制到剪贴板
        navigator.clipboard.writeText(e.target?.dataset?.copy);
        this.$message.success("复制成功!");
      }
    },
  },
  watch: {
    content: {
      immediate: true,
      handler() {
        this.updateMarkdown();
      },
    },
  },
  mounted() {
    this.$refs.contentRef.addEventListener("click", this.handleCopyClick);
  },
  beforeDestroy() {
    this.$refs.contentRef.removeEventListener("click", this.handleCopyClick);
  },
};
</script>

<style lang="scss">
.markdown-view {
  font-family: PingFang SC;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.6rem;
  letter-spacing: 0em;
  text-align: left;
  color: #3b3e55;
  max-width: 100%;
  pre {
    position: relative;
  }
  pre code.hljs {
    width: auto;
  }
  code.hljs {
    border-radius: 6px;
    padding-top: 20px;
    width: auto;
  }
  p,
  code.hljs {
    margin-bottom: 16px;
  }
  p {
    margin: 0;
    margin-bottom: 3px;
  }
  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    color: var(--color-G900);
    margin: 24px 0 8px;
    font-weight: 600;
  }
  h1 {
    font-size: 22px;
    line-height: 32px;
  }
  h2 {
    font-size: 20px;
    line-height: 30px;
  }
  h3 {
    font-size: 18px;
    line-height: 28px;
  }
  h4 {
    font-size: 16px;
    line-height: 26px;
  }
  h5,
  h6 {
    font-size: 14px;
    line-height: 24px;
  }
  ul,
  ol {
    margin: 0 0 8px 0;
    padding: 0;
    font-size: 14px;
    line-height: 24px;
    color: #3b3e55;
  }
  li {
    margin: 4px 0 0 20px;
    margin-bottom: 1rem;
  }
  ol > li {
    list-style-type: decimal;
    margin-bottom: 1rem;
  }
  ul > li {
    list-style-type: disc;
    font-size: 14px;
    line-height: 24px;
    margin-right: 11px;
    margin-bottom: 1rem;
  }
}
</style>
